﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Linq.Expressions;
using System.Threading;
using System.Web;
using KandaAlpha.Domain.Model.Entities;
using KandaAlpha.Domain.Repository;
using Microsoft.Practices.ServiceLocation;
using Db4objects.Db4o;
using Db4objects.Db4o.Ext;
using Db4objects.Db4o.Linq;

namespace KandaAlpha.Infrastructure.Repository.db4o
{
    public class GenericRepository<T> : IGenericRepository<T> where T : EntityBase
    {

        /// <summary>
        /// Returns the active object container
        /// </summary>
        protected IObjectContainerManager _objectContainerManager;

        public GenericRepository(IObjectContainerManager objectContainerManager)
        {
            _objectContainerManager = objectContainerManager;
        }

        public T Load(Expression<Func<T, bool>> whereCondition)
        {
            return GetQuery().Where(whereCondition).FirstOrDefault();
        }

        public IQueryable<T> GetQuery()
        {
            var query = from T c in _objectContainerManager.ObjectContainer
                        select c;
            return query.AsQueryable();
        }

        /// <summary>
        /// Provides explicit loading of object properties (EF v4.0 feature)
        /// </summary>
        public void LoadProperty(T entity, Expression<Func<T, object>> selector)
        {
            throw new NotImplementedException("Haven't done this yet sorry!");
        }

        public List<T> GetAll()
        {
            return GetQuery().ToList();
        }

        public void Add(T entity)
        {
            _objectContainerManager.ObjectContainer.Store(entity);
        }

        public void Update(T entity)
        {
            _objectContainerManager.ObjectContainer.Store(entity);
        }

        public void Delete(T entity)
        {
            _objectContainerManager.ObjectContainer.Delete(entity);
        }

    }
}
